module.exports = function(uid,room){
	this.uid = uid
	this.room = room
	this.chair = -1
	this.lastRsult = false
	this.handCard = []
	var logicBasic = require("../logic/UNOLogic.js")
	var logic = new logicBasic()
	var local = {}
	local.curNum = false
	local.curCol = false
	local.lastCard = false
	local.curType = false
	var timerList = {}
	//销毁
	this.destroy = function() {
		// console.log("robot destroy : ",timer)
		for(var i in timerList){
			clearTimeout(timerList[i])
		}
	}
	//接收数据
	this.onMessage = function(notify) {
		switch(notify.cmd){
			case "gameBegin":
				this.chair = notify.chair
				this.handCard = notify.handCard
				if(notify.curPlayer == this.chair){
					this.playCard()
				}
			break
			case "nextPlay":
				if(notify.curPlayer === this.chair){
					this.playCard()
				}
			break
			case "playCard":
				if(notify.chair === this.chair){
					// console.log("playCard222 : ",notify)
					if(this.handCard[notify.index].col == notify.card.col && this.handCard[notify.index].value == notify.card.value){
						this.handCard.splice(notify.index,1)
					}else{
						console.log(notify.card)
						console.log(this.handCard)
						console.log(new Error("card Error : "+notify.index))
					}
				}
				local.curNum = notify.curNum
				local.curCol = notify.curCol
				local.lastCard = notify.card
				local.curType = notify.curType
			break
			case "drawCard":
				console.log("抽牌")
				if(notify.chair === this.chair){
					this.handCard = notify.handCard
					console.log(this.handCard)
				}
			break
			case "userReady":
				//开始准备
				// console.log("开始准备")
			break
			case "settlement":
				console.log("settlement !!!")
				this.sendMessage("ready",{},5000)
			break
		}
	}
	this.playCard = function() {
		var arr = logic.getAllWinCardList(this.handCard,local.curNum,local.curCol,local.curType)
		if(arr.length){
			var info = {}
			var tmpIndex = Math.floor(Math.random() * arr.length)
			info.index = arr[tmpIndex].index
			if(this.handCard[info.index].type == "wild"){
				info.col = Math.floor(Math.random() * 4) + 1
			}
			console.log("想打的牌 : ", this.handCard,arr[tmpIndex],info.index)
			this.sendMessage("playCard",info,2500)
		}else{
			this.sendMessage("giveUp",{},1500)
		}
	}
	//发送数据
	this.sendMessage = function(cmd,param,time) {
		time = (Math.random() * 0.3 + 0.7) * time
		var id = (new Date()).getTime()
		timerList[id] = setTimeout(local.timeoutFun(this.room,cmd,this.uid,param,id),time)
	}
	local.timeoutFun  = function(room,cmd,uid,param,id) {
		return function() {
			delete timerList[id]
			room.handle[cmd].call(room,uid,0,param,function() {})
		}
	}
	this.sendMessage("ready",{},3000)
}